package com.sunday.aomicaichang.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.MainActivity;
import com.sunday.member.SessionToken;
import com.sunday.member.entity.Member;
import com.sunday.member.utils.SignUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/9.
 */

public class BindPhoneActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_bar)
    RelativeLayout titleBar;
    @Bind(R.id.edt_phone)
    EditText edtPhone;
    @Bind(R.id.view1)
    View view1;
    @Bind(R.id.imageView)
    ImageView imageView;
    @Bind(R.id.edt_code)
    EditText edtCode;
    @Bind(R.id.view2)
    View view2;
    @Bind(R.id.btn_code)
    TextView btnCode;
    @Bind(R.id.ly_register)
    RelativeLayout lyRegister;
    @Bind(R.id.btn_next)
    TextView btnNext;

    private final static String TAG = "RegisterOneActivity";
    private Context mContext;
    private static final int LOCK_SECS = 60;
    private StaticHandler mHander = null;
    private int lockCount = 0;
    private Timer mTimer = null;
    private TimerTask mTimeTask = null;
    private static final int UPDATE_COUNT_STATUS = 0;
    private boolean isInputPhoneFomat = false;
    private boolean isInputCodeFomat = false;
    //    private String unionId;
    private int type;
    private String token;
    private String logo;
    private String nickName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_bind);
        ButterKnife.bind(this);
        type=getIntent().getIntExtra("type",0);
        token=getIntent().getStringExtra("token");
        logo=getIntent().getStringExtra("logo");
        nickName=getIntent().getStringExtra("nickName");
        mContext = this;
        mHander = new StaticHandler(this);
        addTextChangedListener();
    }
    @OnClick({R.id.btn_code,R.id.btn_next})
    void onClick(View v){
        switch (v.getId()) {
            case R.id.btn_code:
                sendCode();
                break;
            case R.id.btn_next:
                next();
                break;
        }
    }

    private void addTextChangedListener() {
        edtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edtPhone.getText().toString().length() > 11) {
                    ToastUtils.showToast(mContext, "手机号码最多11位");
                    int i = editable.toString().length() - 1;
                    editable.delete(i, i + 1);
                }
                if (edtPhone.getText().toString().length() == 11)
                    isInputPhoneFomat = true;
                else
                    isInputPhoneFomat = false;

                checkInputState();
            }
        });

        edtCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edtCode.getText().toString().length() > 6) {
                    ToastUtils.showToast(mContext,  "验证码最多6位");
                    int i = editable.toString().length() - 1;
                    editable.delete(i, i + 1);
                }
                if (edtCode.getText().toString().length() == 4)
                    isInputCodeFomat = true;
                else
                    isInputCodeFomat = false;

                checkInputState();
            }
        });
    }

    private void checkInputState() {
//        if (isInputPhoneFomat && isInputCodeFomat)
//            btnNext.setEnabled(true);
//        else
//            btnNext.setEnabled(false);
    }

    private void sendCode() {
        if (edtPhone.getText().toString().length() < 11) {
            ToastUtils.showToast(mContext,  "请输入11位手机号码");
            return;
        }
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"mobile","type","nonce"};
        String[] str2 = new String[]{edtPhone.getText().toString(),"1", nonce};
        showLoadingDialog(0);
        Call<ResultDO> call= ApiClient.getApiAdapter().send(edtPhone.getText().toString(),1,
                nonce, SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish||response.body()==null){return;}
                ResultDO resultDO=response.body();
                if (resultDO.getCode()==0){
                    startCountdown(UPDATE_COUNT_STATUS);
                }else {
                    ToastUtils.showToast(mContext,resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }



    private void next() {
        Call<ResultDO> call= ApiClient.getApiAdapter().check(edtPhone.getText().toString(),1,
                edtCode.getText().toString());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish||response.body()==null){return;}
                ResultDO resultDO=response.body();
                if (resultDO.getCode()==0){
        Call<ResultDO<Member>> call2= ApiClient.getApiAdapter().loginWithThirdTwo(token,nickName,logo,type,edtCode.getText().toString(),edtPhone.getText().toString());
        call2.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call2, Response<ResultDO<Member>> response) {
                dissMissDialog();
                if (isFinish||response.body()==null){return;}
                ResultDO<Member> resultDO=response.body();
                if (resultDO.getCode()==0){
                    SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                    BaseApp.getInstance().setMember(resultDO.getResult());
                    SessionToken.accountId= String.valueOf(resultDO.getResult().getId());
                    SessionToken.token=resultDO.getResult().getToken();
                    intent=new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                }else {
//                    ToastUtils.showToast(mContext,resultDO.getMessage());
                Intent intent=new Intent(mContext,SetPasswordActivity.class);
                intent.putExtra("type",type);
                intent.putExtra("token",token);
                intent.putExtra("logo",logo);
                intent.putExtra("nickName",nickName);
                intent.putExtra("code",edtCode.getText().toString());
                intent.putExtra("phone",edtPhone.getText().toString());
                startActivity(intent);
                finish();
            }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call2, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }else {
        ToastUtils.showToast(mContext,resultDO.getMessage());
    }
}

    @Override
    public void onFailure(Call<ResultDO> call, Throwable t) {
        dissMissDialog();
        ToastUtils.showToast(mContext,R.string.network_error);
    }
});

    }

    private static class StaticHandler extends Handler {
        WeakReference<BindPhoneActivity> mActivity;

        StaticHandler(BindPhoneActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            BindPhoneActivity activity = mActivity.get();
            if (null == activity)
                return;

            if (msg.what == UPDATE_COUNT_STATUS) {
                activity.updateUICount();
                //
                if (activity.lockCount == LOCK_SECS) {
                    activity.stopCountdown(UPDATE_COUNT_STATUS);
                }
                activity.lockCount++;
            }
        }
    }

    private void startCountdown(final int id) {

        btnCode.setEnabled(false);
        if (mTimer == null)
            mTimer = new Timer();

        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }

        if (mTimeTask == null) {
            mTimeTask = new TimerTask() {
                @Override
                public void run() {
                    sendUpdateUIMessage(id);
                }
            };
        }
        mTimer.schedule(mTimeTask, 0, 1000);

    }

    private void sendUpdateUIMessage(int id) {
        if (mHander != null) {
            Message message = Message.obtain(mHander, id);
            mHander.sendMessage(message);
        }
    }

    public void stopCountdown(int id) {
        if (null != mTimer) {
            mTimer.cancel();
            lockCount = 0;
            mTimer = null;
            mTimeTask = null;
        }
        btnCode.setEnabled(true);
        btnCode.setText("获取验证码");
    }

    private void updateUICount() {
        String str = "" + String.valueOf(LOCK_SECS - lockCount) + "";
        btnCode.setText(str + "s");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }
        if (null != mTimer) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}


